<?php
/**
 * 公用控制器
 */
class BaseAction extends Action{
    public $accountId;
    public $userId;
    public function _initialize()
    {
        $ef=$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].(json_encode($_POST));
        wLog('curl-put call sd2:' . $ef, 'httpCurldd');
        $tablenoId = $this->_get('tableno_id');
        $openId = $this->_get('openid');
        $resId = $this->_get('res_id');
        $sig = $this->_get('sig');
        session('openId', $openId);
        $params = array(
            'res_id' => $resId,
            'tableno_id' => $tablenoId,
            'openid' => $openId,
        );

        if (!$openId) {
            //$this->error('身份信息丢失');
        }

//        if (!$sig) {
//            $this->error('签名丢失');
//        }
//
//        if ($sig) {
//            //获得签名
//            $sign = $this->getSign($params);
//
//            if ($sign != $sig) {
//                $this->error('签名错误');
//            }
//        }
        $this->login($openId);

    }


    /**
     * 用户登陆
     */
    public function login($openId='')
    {
        if (!session('?user_id')) {
            $this->getUserInfo($openId);
          $mUser = D('User');
          //没有登录过，查找用户表 有存session 没有从新获取
          $userId = $mUser->where(array('open_id' => $openId))->getField('user_id');

          if ($userId) {
              session('userId', $userId);
          } else {
              $this->getUserInfo($openId);
          }
    }
      if ($this->isWechatBrower()) {
          //判断用户登录过没有

          if (!session('?user_id')) {

              $mUser = D('User');
              //没有登录过，查找用户表 有存session 没有从新获取
              $userId = $mUser->where(array('open_id' => $openId))->getField('user_id');

              if ($userId) {

                  session('userId', $userId);
              } else {

                  $this->getUserInfo($openId);
              }
          }
      } else {
          //$this->error('用户登陆暂只支持微信登陆，请用微信重新打开');
      }
    }

    /**
     * @param string $openId 用户open_id
     * @throws Exception 获取用户信息
     */
    function getUserInfo($openId=''){
        $time = time();
        $list = array(
            'c'=>'smart',
            'a'=>'getMember',
            'type'=>1,
            'number'=>$openId,
            'time'=>$time,

        );
        $sign = $this->getSign($list);
        $url='http://www.zulg.com/api.php?c=smart&a=getMember&type=1&number='.$openId.'&time='.time().'&sig='.$sign;

        $users=$this->curl($url);

        $code = $users['code'];
        // $code 1 成功 2 无该用户信息 -1 校验不正确 -2 数据不正确
        if($code == 1){
            if(!$users['userinfo']['StudentNo']){
                header("Location:http://www.3797zju.net/m/Member/Bind");
                exit;
            }
            $info = array(
                'open_id' => $users['userinfo']['OpenId'],   //微信open_id
                'StudentNo' => $users['userinfo']['StudentNo'], //学工号
                'name' => $users['userinfo']['Name'], //名字
                'standing' => $users['userinfo']['Standing'], //身份类型
                'mobile' => $users['userinfo']['Mobile'], //电话
                'phone' => $users['userinfo']['Phone'], //手机
                'unionid' => $users['userinfo']['unionid'], //用户微信的unionid
                'cardno' => $users['userinfo']['CardNo'], //用户卡号
            );
            $userId = M('User')->add($info);
            if($userId){
                session('userId',$userId);
            }
        }elseif($code == 2){
            header("Location:http://www.3797zju.net/m/Member/Bind");
            exit;
        }
    }

    /**
     * @param $params  数组参数
     * @return string  获取签名
     */
    public function getSign($params,$type=''){

        $str = '';
        if($type==1){
            $str .= 'c=smarta=publicSendMsg';
        }
        foreach($params as $k=>$v){
            $str .= $k . '=' .$v;
        }

        $str .='smart123456';

        $sign=md5($str);
        return $sign;
    }


    /**
     * http请求
     * @param $url 请求地址
     * @param null $postFields 请求参数
     * @return mixed
     * @throws Exception
     */
    public function curl($url = '', $postParams= null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT,30);
        curl_setopt($ch, CURLOPT_HEADER,0);
        // post提交数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postParams);
        if(!is_array($postParams)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postParams)
            ));
        }
        $output = json_decode(curl_exec($ch),true);
        curl_close($ch);
        //打印获得的数据
        return $output;
    }






    /**
     * 获取cookie
     */
    public function g_cookie($name){
        $ck = $_COOKIE[$name];
        $cookie =  unserialize($ck);
        return $cookie;
    }
    /**
     * 设置cookie
     */
    public function s_cookie($name,$cookie){
        $coke = serialize($cookie);
        setcookie($name,$coke,time ()+ 2678400,'/');
    }

    /**
     * 判断是否是微信浏览器
     * @return boolean
     */
    public function isWechatBrower()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') != false) {
            return true;
        } else {
            return false;
        }
    }

    public function logout(){
        // 销毁登陆信息
        session('accountId', null);
        session('userId', null);
        session('wechatUserId', null);
        session('wechatId', null);
        session('openId',null);
        session('accountEnName',null);
        session('alipayId',null);
        session('alipayUserId',null);
    }

    /**
     * 判断是否是支付宝浏览器
     * @return boolean
     */
    public function isAlipayBrower()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') != false) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 判断用户是否登陆
     * @return boolean
     */
    public function isLogin()
    {
//		if ($this->accountId == session('accountId') &&
//            ($_SESSION['alipayUserId'] || $_SESSION['wechatUserId']) &&
//            $_SESSION['userId']
//        ) {
//			return true;
//		}else{
//			return false;
//		}

        if ($this->accountId == session('accountId') &&
            ($_SESSION['alipayUserId'] || $_SESSION['wechatUserId'])
        ) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 微信网页授权登陆
     */
    public function wechatLogin(){
        $authCode = $this->_get('code');
        $mWechat = D('Wechat/Wechat');
        $wechatInfo = $mWechat->getByAccountId($this->accountId);

        session('wechatId', $wechatInfo['wechat_id']);
        session('accountId', $wechatInfo['account_id']);
        if(!$authCode){
            // 模拟登录获取code
            //echo '++++'.$this->accountId;die();
            $appid = $mWechat->getFieldByAccountId($this->accountId,'appid');
//            wLog(date('Y-m-d H:i:s').'data:'.var_export($this->accountId,true),'wechatapi');
//            wLog(date('Y-m-d H:i:s').'data:'.var_export($appid,true),'wechatapi');
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.
                '&accountId='.$this->accountId.'&redirect_uri='.urlencode(session('redirectUrl')).
                '&response_type=code&scope=snsapi_base&state=repair#wechat_redirect';

            session('snsapiBase',true);
            header('Location: '.$url);
            exit;
        }else{
            // 获取公众号信息
            $mWechatUser = D('Wechat/WechatUser');

            // 引用微信接口文件
            vendor('Wechat.WechatApi');
            $cWechat = new WechatApi($wechatInfo['wechat_id']);
            if(session('?snsapiBase')){
                // 获取用户openid
                $info = $cWechat->getUserInfoByAuth($authCode, false);
                if($info['status'] != 'S'){
                    $this->error('用户信息获取错误，请稍后再试');
                }

                $openid = $info['data'];
                $condition = array(
                    'wechat_id' => $wechatInfo['wechat_id'],
                    'openid' => $openid,
                );
                $wechatUserInfo = $mWechatUser->getInfo($condition);
                session('snsapiBase', null);
                if(!$wechatUserInfo){
                    // 用户首次访问，重新跳转网页授权获取用户信息
                    $redirectUrl = session('redirectUrl');
                    $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wechatInfo['appid'].'&redirect_uri='.urlencode($redirectUrl).'&response_type=code&scope=snsapi_userinfo&state=repair#wechat_redirect';
                    header('Location: '.$url);
                    //            wLog(date('Y-m-d H:i:s').'data:'.var_export($url,true),'wechatapi');
                    exit;
                }elseif(!$wechatUserInfo['subscribe']){
                    // 未关注的老用户的关注状态验证
                    $res = $cWechat->getUserInfo($openid);
                    if($res['status'] == 'S'){
                        if(!$wechatUserInfo['subscribe'] && $res['data']['subscribe']){
                            $update = array(
                                'wechat_id' => session('wechatId'),
                                'wechat_user_id' => $wechatUserInfo['wechat_user_id'],
                                'type' => 1,
                                'subscribe' => 1,
                                'last_subscribe_time' => $res['data']['subscribe_time'],
                                'group_id' => $res['data']['groupid'],
                                'avatar' => $res['data']['headimgurl']
                            );
                            $mWechatUser->update($update);
                        }
                    }
                }
            }else{
                // 网页授权获取新用户信息
                $res = $cWechat->getUserInfoByAuth($authCode, false);
                $openid = $res['data'];
                $info = $cWechat->getUserInfo($openid);
                $result = $info['data'];
                //$openid = $result['openid'];
                if($info['status'] == 'F'){
                    $this->error($info['message']);
                }elseif(!$openid){
                    $this->error('网页授权获取用户信息失败，请稍后重试');
                }else {
                    session('wx_header',$result['headimgurl']);
                }

                // 插入用户信息
                $result['wechat_id'] = session('wechatId');
                $result['avatar'] = $result['headimgurl'];
                $wechatUserInfo = $mWechatUser->update($result);

                if(empty($wechatUserInfo)){
                    $this->error('用户信息更新错误，请稍后再试');
                }
            }

            // 登陆成功
            session('wechatUserId', $wechatUserInfo['wechat_user_id']);
            session('userId', $wechatUserInfo['user_id']);
            session('openId', $openid);
            $accountEnName = D('Account')->where(array('account_id'=>$this->accountId))->getField('account_en_name');
            session('accountEnName',$accountEnName);

            // 重置至用户访问的地址，防止authCode失效，刷新失败
            if(session('?redirectUrl')){
                header('Location: '.session('redirectUrl'));
                exit;
            }

        }

    }

    /**
     * 支付宝网页授权登陆
     */
    public function alipayLogin()
    {
        $authCode = $this->_get('auth_code');
        //判断该账号是否是校园卡
        $dataAccount = M("Account")->where(array("account_id"=>$this->accountId))->find();
        wLog(date("Y-m-d H:i:s") ." account_id dataAccount: ".M()->_sql(),"AlipayApi");
        $alipayInfo = M('Alipay')->where(array('account_id' => $this->accountId))->find();
        $alipayId = $alipayInfo['alipay_id'];
        if($dataAccount['is_campuscard'] ==1 ){ //校园卡
            $alipayInfo = M('AlipayCampuscard')->where(array('account_id' => $this->accountId,"campus_type"=>1))->find();
        }
        if(empty($alipayInfo)){
            $this->error('支付宝账户未配置');
        }

        if (!$authCode) {
            $appid = $alipayInfo['appid'];
            $url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $appid . '&scope=auth_user,auth_ecard&redirect_uri=' . session('redirectUrl');
            header('Location: ' . $url);
            exit;
        }else{
            $mAlipayUser = D('Alipay/AlipayUser');
            // 获取支付宝用户信息
            vendor('Alipay.AlipayApi');
            $cAlipay = new AlipayApi('','',$alipayInfo);
            $return = $cAlipay->getUserInfoByAuth($authCode);
            if ($return['status'] == 'F') {
                $this->error($return['message']);
            }

            // 转换用户信息数据包
            $infoData = $return['data'];
            $sex = 0;
            if($infoData['gender'] == 'm'){
                $sex = '1';
            } elseif($infoData['gender'] == 'F'){
                $sex = '2';
            }
            $isCertified = 0;
            if($infoData['is_certified'] == 'T'){
                $isCertified = 1;
            }

            $isStudentCertified = 0;
            if($infoData['is_student_certified'] == 'T'){
                $isStudentCertified = 1;
            }

            $update = array(
                "alipay_id"=>$alipayId,
                "original_alipay_user_id"=>$infoData['user_id'],
                "avatar"=>$infoData['avatar'],
                "sex"=>$sex,
                "nickname"=>$infoData['nick_name'],
                "province"=>$infoData['province'],
                "city"=>$infoData['city'],
                "user_type_value"=>$infoData['user_type'],
                "is_certified"=>$isCertified,
                "is_student_certified"=>$isStudentCertified,
                "user_status"=>$infoData['user_status'],
                "access_token"=>$infoData['access_token'],
                "expires_in_time"=>$infoData['expires_in_time'],
            );
            if($infoData['cert_no']){
                $update['user_name'] = $infoData['user_name'];
                $update['idcard'] = $infoData['cert_no'];
            }
            $alipayUserInfo = $mAlipayUser->where(array("original_alipay_user_id"=>$infoData['user_id'],"alipay_id"=>$alipayId))->find();
            if($alipayUserInfo){
                // 更新用户信息
                $mAlipayUser->where(array("alipay_user_id"=>$alipayUserInfo['alipay_user_id']))->save($update);
            } else {
                $update['create_time'] = time();
                //添加用户信息
                $alipayUserId = $mAlipayUser->add($update);
                $alipayUserInfo['alipay_user_id'] = $alipayUserId;
            }
            // session存储账号ID，作为数据插入前分表判断依据
            session('accountId', $this->accountId);
            // session存储服务窗ID
            session('alipayId', $alipayId);
            // 登陆成功
            session('alipayUserId', $alipayUserInfo['alipay_user_id']);

            //重新查一遍查询包括user_id的值
            //$alipayUserInfo = $mAlipayUser->getByAlipayUserId($alipayUserInfo['alipay_user_id']);

            //如果有user_id的话就赋值，添加必定没有，修改可能有
            session('userId', $alipayUserInfo['user_id']);
        }
    }

    /**
     * 用户认证验证
     */
    public function auth(){
        $mUser = D('User');
        $userInfo = $mUser->getByPk(session('userId'));
        if (!$userInfo['real_name'] || !$userInfo['mobile']){
            $userInfo['type'] = 0;
//			$mUser->where(array('user_id'=>session('userId')))->save(array('status'=>0,'type'=>0));
        }
        $authUrl = U('base/user/register',array('account_id' => $this->accountId,'type'=>$userInfo['type']));
        $presentUrl = GROUP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME; //当前链接URL
        if( ($userInfo['status'] !=2 || !session('userId') ) && $presentUrl != 'Base/User/register') {
            //echo $authUrl;die();
            // 用户未认证
            $this->redirect($authUrl);
            exit;
        }
//		if(!$userInfo['status'] && $presentUrl != 'Base/User/register'){
//			$this->redirect($authUrl);
//			exit;
//		}
    }

    /**
     * 是否是丁丁浏览器
     * @return string
     */
    public function isDingBrowser()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'DingTalk') != false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取订单编号
     * @param string $moduleName
     * @return array
     */
    public function getOrderSn($moduleName){
        // 14位时间戳
        $datatime = date('YmdHis');
        // 3位模块ID
        $moduleData = $this->getModuleIdByModuleName($moduleName);
        if($moduleData['status'] == 'S'){
            $moduleId = str_pad($moduleData['data'], 3, '0', STR_PAD_LEFT);
        }else{
            return $moduleData;
        }
        // 2位账号ID
        $accountShortId = str_pad(substr(session('accountId'), -2), 2, '0', STR_PAD_LEFT);
        // 4位用户ID
        $userFullId = str_pad(substr(session('userId'), -4), 4, '0', STR_PAD_LEFT);
        // 1位支付方式
        if($this->isWechatBrower()){
            $payType = 1;
        }elseif($this->isAlipayBrower()){
            $payType = 2;
        }else{
            $payType = 0;
        }
        // 4位随机数
        $rand = rand(1000, 9999);
        $orderSn = $datatime.$moduleId.$accountShortId.$userFullId.$payType.$rand;
        if(strlen($orderSn) != 28){
            return array('status' => 'F', 'message'=>'订单编号生成异常');
        }
        return array('status' => 'S', 'data' => $orderSn);
    }

    /**
     * 通过模块名称获取模块ID
     * @param string $moduleName
     * @return array
     */
    public function getModuleIdByModuleName($moduleName){
        $moduleId = D('Module')->getFieldByModuleName($moduleName, 'module_id');
        if($moduleId){
            return array('status' => 'S', 'data' => $moduleId);
        }else{
            return array('status' => 'F', 'message' => '模块不存在');
        }
    }

    /**
     * 订单支付
     * @param array $payData
     * @return array
     */
    public function pay($payData){
        // 数据包不为空验证
        if(empty($payData)){
            return array('status' => 'F', 'message' => '支付数据包不能为空');
        }

        if($this->isWechatBrower()){
            return $this->wechatPay($payData);
        }elseif($this->isAlipayBrower()){
            return $this->alipayPay($payData);
        }else{
//			return $this->alipayPay($payData);
            return array('status' => 'F', 'message' => '当前支付只支持微信或支付宝钱包支付');
        }
    }

    /**
     * 微信支付
     * @param array $payData
     * @return array
     */
    public function wechatPay($payData){
        if (isset($payData['is_special']) && $payData['is_special'] == '0') {
            $payService = Service('Pay/WxPay');
            return $payService->wechatNormalPay($payData);
        }

        $verifyField = array(
            'parentAppid',			// 母商户ID
            'parentMchId',			// 母商户商户ID
            'parentKey',			// 母商户KEY
            'subOpenid',			// 用户在子商户下的微信openid
            'subAppid',				// 子商户ID
            'subMchId',				// 子商户商户ID
            'orderName',			// 订单名称
            'orderSn',				// 订单编号
            'orderAmount',			// 订单金额
        );
        foreach($verifyField as $key => $value){
            if(empty($payData[$value])){
                return array('status' => 'F', 'message' => $value . '不能为空');
            }
        }
        // 组建支付传输数据包
        $notifyUrl = C('site_url').U('wechat/wechat_pay/notify');
        vendor('Wechat.WechatPay');
        $cWechatPay = new WechatPay($payData['parentAppid'], $payData['parentMchId'], $payData['parentKey'], $notifyUrl);
        $cWechatPay->setParameter("sub_openid", $payData['subOpenid']);
        $cWechatPay->setParameter("sub_appid", $payData['subAppid']);
        $cWechatPay->setParameter("sub_mch_id", $payData['subMchId']);
        $cWechatPay->setParameter("body", $payData['orderName']);
        $cWechatPay->setParameter("out_trade_no", $payData['orderSn']);
        $cWechatPay->setParameter("total_fee", $payData['orderAmount'] * 100);
        $cWechatPay->setParameter("notify_url", $notifyUrl);
        $cWechatPay->setParameter("trade_type", "JSAPI");
        $prepayData = $cWechatPay->getPrepayId();
        if($prepayData['status'] == 'S'){
            $prepayId = $prepayData['data'];
        }else{
            return array('status' => 'F', 'message' => $prepayData['message'] ? $prepayData['message'] : '微支付系统繁忙，请联系管理员');
        }
        $cWechatPay->setPrepayId($prepayId);
        $jsApiParameters = $cWechatPay->getParameters();
        wLog('jsApiParam:'.var_export($jsApiParameters,true),'wxPay');

        return array('status' => 'S', 'data' => $jsApiParameters);
    }

    public function alipayPay($payData){
        $verifyField = array(
            'partner',				// 合作者支付宝账号ID
            'sellerId',				// 卖家支付宝用户号
            'returnUrl',			// 页面跳转同步通知页面路径
// 				'externToken',			// 手机支付宝token
            'orderName',			// 订单名称
            'orderDesc',			// 订单描述
            'orderSn',				// 订单编号
            'orderAmount',			// 订单金额
        );
        foreach($verifyField as $key => $value){
            if(empty($payData[$value])){
                return array('status' => 'F', 'message' => $value.'不能为空');
            }
        }
        $notifyUrl = C('site_url').U('alipay/alipay_pay/notify');
        $parameter = array(
            "service" => "alipay.wap.create.direct.pay.by.user",
            "partner" => trim($payData['partner']),
            "seller_id" => trim($payData['sellerId']),
            "payment_type" => 1,
            "notify_url" => $notifyUrl,
            "return_url" => $payData['returnUrl'],
            "out_trade_no" => $payData['orderSn'],
            "subject" => $payData['orderName'],
            "total_fee" => $payData['orderAmount'],
            "body" => $payData['orderDesc'],
            "it_b_pay" => '1d',
            "_input_charset" => 'UTF-8',
        );
        vendor('Alipay.AlipayPay');
        $cAlipayPay = new AlipayPay($this->accountId);
        $return = $cAlipayPay->pay($parameter);
    }

    /**
     *微信发红包
     * @param int $accountId
     * @param string $openid
     * @param float $money      红包金额
     * @param string $wishing  祝福语
     * @param string $actName  活动名称
     * @param string $remark   备注
     * @return array $res
     */
    public function sendRedToUser($accountId,$openid,$money,$wishing,$actName,$remark){
        if(!$accountId || !$openid || !$money){
            return array('status' => 'F','message' => '缺少必要的参数');
        }

        if(strlen($wishing) > 128){
            return array('status' => 'F','message' => '祝福语字数超过限制');
        }

        if(strlen($actName) > 32){
            return array('status' => 'F','message' => '活动名称字数超过限制');
        }

        if(strlen($remark) > 256){
            return array('status' => 'F','message' => '备注信息字数超过限制');
        }

        vendor('Wechat.WechatApi');
        $wechat = D('Wechat/Wechat')->getInfo(array('account_id' => $accountId));
        $weixin = new WechatApi($wechat['wechat_id']);

        $array['mch_billno'] = $wechat['parent_mch_id'] . date('YmdHis') .mt_rand(1000,9999);
        $array['mch_id'] = $wechat['parent_mch_id'];
        $array['sub_mch_id'] = $wechat['mch_id'];
        $array['wxappid'] = $wechat['parent_appid'];
        $array['msgappid'] = $wechat['appid'];
        $array['send_name'] = $wechat['wechat_name'];
        $array['re_openid'] = $openid;
        $array['total_amount'] = $money * 100;
        $array['min_value'] = $money * 100;
        $array['max_value'] = $money * 100;
        $array['wishing'] = $wishing;
        $array['act_name'] = $actName;
        $array['remark'] = $remark;
        $res = $weixin->send_redpacket($array);
        return $res;
    }

    /**
     * 共用赋值与渲染
     */
    public function view($data){
        $this->assign('data',$data);
        $this->display();
    }

    /**
     * 新版支付订单支付
     * @param string $orderSn  订单编号
     * @param string $title    订单名称
     * @param string $accountId  账号id
     * @param string $notifyUrl  异步回调地址
     * @param string $returnUrl  同步回调地址
     * @param string $returnUrl  微信分账（zym/wika 2017/8/7）
     * @return array
     */
    public function newPay($accountId = '',$orderSn='',$title='订单支付',$notifyUrl = '',$returnUrl = '',$ledger = array()){
        if(!isset($accountId)){
            $accountId = session('accountId');
        }
        $payFactory = Service('Pay/PayFactory');
        if($this->isWechatBrower()){
            return $payFactory->createObj('weixin',$accountId,$orderSn,$title,$notifyUrl,$returnUrl,$ledger);
        }elseif($this->isAlipayBrower()){
            return $payFactory->createObj('alipay',$accountId,$orderSn,$title,$notifyUrl,$returnUrl);
        }else{
//			return $this->alipayPay($payData);
            return array('status' => 'F', 'message' => '当前支付只支持微信或支付宝钱包支付');
        }
    }

    /**
     * 清除重复的用户数据，避免用户支付串号
     */
    public function  clearSameUser()
    {
        $condition = array(
            'user_id'=>session('userId'),
            'wechat_user_id'=>array('neq',session('wechatUserId'))
        );
        $count = D('Wechat/WechatUser')->where($condition)->count();
        if ($count > 0) {
            D('Wechat/WechatUser')->where($condition)->save(array('user_id' => 0));
        }
    }

    /**
     * 是否需要强关判断
     */
    public function focus($shorthand)
    {
        $id = M('AccountMenuFocus')->where(array('account_id'=>$this->accountId,'shorthand'=>$shorthand))->getField('id');
        if ($id){
            $subscribe = M('WechatUser')->where(array('wecaht_user_id'=>session('wechatUserId')))->getField('subscribe');
            if ($subscribe != 1){
                $url = U('/base/subscribe/index',array('account_id'=>$this->accountId));
                R($url);
            }
        }
    }
}
